/**
 * Created by huotaol on 2017/5/19.
 */
import React, {Component} from "react";
import {Alert, ListView, StyleSheet, View} from "react-native";
import ModuleCommonHeader from "../../../main/module/ModuleCommonHeader";
import {Actions} from "react-native-router-flux";
import CustomStyle from "../../../../common/style/CustomStyle";
import Util from "../../../main/Util";
import * as StorageConstant from "../../../constant/Storage";
import {connect} from "react-redux";
import {setLoadingState} from "../../../redux/action/homePage";
import CarListItem from "../../../main/record/common/CarListItem";


const DATA_SOURCE = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
const SAVE_KEY = StorageConstant.STORAGE_RECORD_SIMPLE;

class RecordList extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            data: [],
        };
        this._loadData = this._loadData.bind(this);
        this._enterDetail = this._enterDetail.bind(this);
        this._deleteData = this._deleteData.bind(this);
        Util.storage.load({
            key: 'carjson',
            id: '1000'
        }).then(ret => {
            Util.parseCarJson(ret);
        }).catch(err => {
            let carJson = require('../../../../configs/dataLite.json');
            Util.parseCarJson(carJson);
            carJson = null;
        });
        console.log('RecordList constructor ' + JSON.stringify(props));
    }

    componentDidMount() {
        this._loadData();
        console.log('RecordList componentDidMount ');
    }

    componentDidUpdate() {
        console.log('RecordList componentDidUpdate ' + JSON.stringify(this.props));
    }

    componentWillReceiveProps() {
        console.log('RecordList componentWillReceiveProps ' + JSON.stringify(this.props));
        this._loadData();
    }

    render() {
        console.log('RecordList render ' + JSON.stringify(this.state.data));
        return (
            <View style={{flex: 1}}>
                <ModuleCommonHeader title={'已录入车辆'} rightText={'新增'} clickedRight={() => {
                    this._enterDetail();
                }}/>
                <ListView
                    initialListSize={5}
                    dataSource={DATA_SOURCE.cloneWithRows(this.state.data)}
                    renderRow={(rowData) => this._renderRow(rowData)}
                />
            </View>
        );
    }

    _renderRow(item) {
        return <CarListItem object={item}
                            showPush={true}
                            onClickedListener={() => this._enterDetail(item)}
                            onClickedUploadListener={() => this._uploadData(item)}
                            onClickedDeleteListener={() => this._deleteData(item)}
                            push={() => this._push(item)}
                            onClickedQAListener={() => this._enterQA(item)}
        />
    }

    _enterDetail(item = {}) {
        Actions.RecordSimpleRoot({
            saveKey: SAVE_KEY,
            carData: item,
        });
    }

    _loadData() {
        Util.storage.getAllDataForKey(SAVE_KEY)
            .then(ret => {
                this.setState({data: ret.reverse()});
            });
    }

    _deleteData(data) {
        Alert.alert(
            '确认删除吗？',
            '车辆数据一旦删除就无法找回了',
            [
                {
                    text: '取消', onPress: () => {
                }
                },
                {
                    text: '确认删除', onPress: () => {
                    Util.storage.remove(
                        {
                            key: SAVE_KEY,
                            id: data.saveId
                        }
                    );
                    this._loadData();
                }
                },
            ]
        );
    }

    _enterQA(rowData) {
        Actions.QaRoot({
            saveKey: SAVE_KEY,
            saveData: rowData,
        });
    }


    _push(rowData) {
        console.log('RecordList _push    ' + JSON.stringify(rowData));
        this.props.setLoading(true, '推送中...');
        const param = {
            carid: rowData.carid,
        };
        console.log('RecordList _push ' + JSON.stringify(param));
        Util.postServer('user/bksmspush', param, result => {
            Util.showToast('推送成功');
            this.props.setLoading(false, '');
        }, msg => {
            Util.showToast(msg);
            this.props.setLoading(false, '');
        });
    }

    _uploadData(rowData) {
        // 设置基本信息的type，并保存数组
        rowData.basicinfo.type = {name: '', value: '400'};
        this.props.setLoading(true, '上传图片中...');
        this.timer = setTimeout(
            () => {
                this.timer && clearTimeout(this.timer);
                Util.uploadImages(rowData, () => {
                    console.log('RecordedCarList  success');
                    this.onImageUploadSuccess(rowData);
                }, (err) => {
                    console.log('RecordedCarList failed ');
                    this.onImageUploadFailed(err)
                });
            }, 500
        );
    }

    onImageUploadSuccess(rowData) {
        // 把表征里程赋值到基本信息里
        rowData.basicinfo.travelkilometer.value = rowData.carconfig[1].value;
        const user = Util.getUser();
        let params = {
            token: user.token,
            userid: user.id,
            basicinfo: Util.makeBasicParams(rowData),
            expandinfo: Util.makeExpandParams(rowData, Util.checkQainfo(rowData) === Util.OK),
            carid: rowData.carid ? rowData.carid : '0',
        };
        this.props.setLoading(true, '上传数据中...');
        console.log('RecordedCarList onImageUploadSuccess ');
        Util.postServer('user/issuebangkan', params, (result) => {
            this.onDataUploadSuccess(rowData, result)
        }, (msg) => this.onDataUploadFailed(msg));
    }

    onImageUploadFailed(err) {
        this.props.setLoading(false, '');
        Util.showToast('上传图片失败[' + err + ']');
    }

    onDataUploadSuccess(rowData, result) {
        console.log('RecordedCarList onDataUploadSuccess ' + JSON.stringify(result));
        this.props.setLoading(false, '');
        if (result.status === '0' || result.status === 0) {
            Util.showToast('车辆数据上传成功');
            rowData.carid = result.data.carid;
            Util.saveData(SAVE_KEY, rowData);
            this._loadData();
        } else {
            Util.showToast('上传数据失败:' + result.msg);
        }
    }

    onDataUploadFailed(msg) {
        this.props.setLoading(false, '');

        Util.showToast('上传数据失败[' + msg + ']');

    }

}

const styles = StyleSheet.create({
    btContainer: {
        borderRadius: 10,
        borderTopWidth: 1,
        borderLeftWidth: 1,
        borderRightWidth: 1,
        borderBottomWidth: 1,
        width: CustomStyle.getActualSizeInHorizontal(160),
        height: CustomStyle.getActualSizeInVertical(72),
        alignItems: 'center',
        justifyContent: 'center',
        marginTop: CustomStyle.getActualSizeInVertical(16),
    },
    btText: {
        fontSize: CustomStyle.getActualFontSize(30),
        color: '#fff',
    },
});

const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {
        setLoading: (loading, text) => {
            dispatch(setLoadingState(loading, text));
        },
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(RecordList);